package com.example.springsecurity.common.config;

import com.alibaba.fastjson2.JSON;
import com.example.springsecurity.entity.*;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @Description：系统默认数据配置类，主要用于初始化用户、角色、菜单等系统数据
 * @Author： fengcheng
 * @Date： 2025/1/17 16:54
 */
@Data
@Component
@ConfigurationProperties(prefix = "system.init.config")
public class SystemInitDataConfig {

    @Resource
    private Environment environment;

    private SystemTenant systemTenant;
    private SystemUser systemUser;
    private SystemRole systemRole;
    private SystemUserRole systemUserRole;
    private List<SystemMenu> systemMenu;
    private List<SystemRoleMenu> systemRoleMenu;

    @PostConstruct
    public void initSystemInitDataConfig() {
        String tenantData = new String(environment.getProperty("system.init.config.tenant").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
        SystemTenant tenantDataObj = JSON.to(SystemTenant.class, tenantData);
        setSystemTenant(tenantDataObj);

        String userData = new String(environment.getProperty("system.init.config.user").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
        SystemUser userDataObj = JSON.to(SystemUser.class, userData);
        setSystemUser(userDataObj);

        String roleData = new String(environment.getProperty("system.init.config.role").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
        SystemRole roleDataObj = JSON.to(SystemRole.class, roleData);
        setSystemRole(roleDataObj);

        String userRoleData = new String(environment.getProperty("system.init.config.user_role").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
        SystemUserRole systemUserRole = JSON.to(SystemUserRole.class, userRoleData);
        setSystemUserRole(systemUserRole);

        String menuData = new String(environment.getProperty("system.init.config.menu").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
        List<SystemMenu> systemMenus = JSON.parseArray(menuData, SystemMenu.class);
        setSystemMenu(systemMenus);

        String roleMenuData = new String(environment.getProperty("system.init.config.role_menu").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
        List<SystemRoleMenu> systemRoleMenus = JSON.parseArray(roleMenuData, SystemRoleMenu.class);
        setSystemRoleMenu(systemRoleMenus);
    }
}
